package org.liaohailong.library.log;

import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;

/**
 * create by liaohailong
 * time 2022/8/24 15:41
 * desc: 本地 log 日志持久化
 */
public class LogFileWriter {

    private final Logcat logcat = Logcat.obtain(this);

    @NonNull
    private final String filepath;

    private final Handler workHandler;
    private final Object writeLock = new Object();


    private RandomAccessFile output;
    private final byte[] rnBytes = "\n".getBytes();

    public LogFileWriter(@NonNull String filepath) {
        this.filepath = filepath;

        HandlerThread ht = new HandlerThread("log-writer");
        ht.start();
        workHandler = new Handler(ht.getLooper());

        prepare();
    }

    private void prepare() {
        try {
            File file = new File(filepath);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                if (!parentFile.mkdirs()) {
                    return;
                }
            }
            if (!file.exists()) {
                if (!file.createNewFile()) {
                    return;
                }
            }
            // 创建fos
            output = new RandomAccessFile(file, "rw");
            output.seek(output.length()); // append模式
        } catch (Exception ex) {
            logcat.exception(ex);
        }
    }

    public void write(String msg) {
        workHandler.post(() -> {
            synchronized (writeLock) {
                if (output == null) {
                    return;
                }
                try {
                    output.write(msg.getBytes(StandardCharsets.UTF_8));
                    output.write(rnBytes);
                } catch (Exception ex) {
                    // ignore
                }
            }
        });
    }
}
